<template>
  <div style="position: relative;width: 100%;height: 100%" class="app-content">
    <div :style="{zIndex:singOutVisible?'2':'5'}" class="user">
      <el-popover
          placement="bottom"
          v-model="popover"
          trigger="click">
        <div class="user-detail">
          <div class="flex">
            <div class="top">
              <div class="flex">
                <p class="img-width"><img src="../assets/images/img1.png" alt=""/></p>
                <p>£ {{ (clientData.balance / 100).toFixed(2) }}</p>
              </div>
              <div class="flex">
                <p class="img-width"><img src="../assets/images/img2.png" alt=""/></p>
                <p>{{ clientData.lastLoginTime | changeTime }}</p>
              </div>
            </div>
            <div class="user-img" v-if="userData">
              <img class="head-img" :src="userData.memberPhoto" alt=""/>
              <img class="bg"
                   :src="require('../assets/images/bgLeave'+(userData.memberLevel <= 5?userData.memberLevel:((Number(userData.memberLevel)/5)-1))+'.png')"
                   alt=""/>
            </div>
            <div class="dan" v-if="userData">
              <p><img :src="require('../assets/images/leave'+(userData.memberLevel <= 5 ?userData.memberLevel:((Number(userData.memberLevel)/5)-1))+'.png')" alt=""
                      class="sign"/>{{ userData.memberLevel | leveChange }}</p>
            </div>
          </div>
          <div class="user-content">
            <p v-if="clientData.avaimins" style="text-align: right">Remaining:<span v-if="Number(clientData.avaimins)/60 >=1">{{(Number(clientData.avaimins)/60).toFixed(2)}}H</span><span v-else>{{clientData.avaimins}}M</span></p>
            <p v-else style="text-align: right">Remaining:0</p>
            <div style="display: flex;justify-content: flex-start;align-items: center">
              <div><img src="../assets/images/dian.png" width="20px"></div>
              <div class="dian-style" style="display: flex;justify-content: space-between;width: 100%;margin-left: 10px">
                <div v-for="i in 26" :key="i" :class="i<=(26*(Number(clientData.avaimins)/Number(clientData.totalmins)))?'hover':''"></div>
              </div>
            </div>
          </div>
          <div>
            <ul>
              <li class="flex" @click="handleLockPc">
                <p class="img-width"><img src="../assets/images/img3.png" alt=""/></p>
                <p>Lock Pc</p>
              </li>
              <li class="flex" @click="handleTopUp">
                <p class="img-width"><img src="../assets/images/img4.png" alt=""/></p>
                <p>Top Up</p>
              </li>
              <li class="flex" @click="handleDownApp">
                <p class="img-width"><img src="../assets/images/img5.png" alt=""/></p>
                <p>Download Sidequest App</p>
              </li>
              <!--              <li class="flex">-->
              <!--                <p class="img-width"><img src="../assets/images/img6.png" alt=""/></p>-->
              <!--                <p>Feedback</p>-->
              <!--              </li>-->
              <li class="flex" @click="handleSignOut">
                <p class="img-width"><img src="../assets/images/img7.png" alt=""/></p>
                <p>Sign Out</p>
              </li>
            </ul>
          </div>
        </div>
        <div slot="reference">
          <img class="head-img" :src="userData.memberPhoto" alt=""/>
          <img class="bg" v-if="userData"
               :src="require('../assets/images/bgLeave'+(userData.memberLevel <= 5?userData.memberLevel:((Number(userData.memberLevel)/5)-1))+'.png')"
               alt=""/>
        </div>
      </el-popover>
      <div>
        <p class="name">{{ userData.nickName }}</p>
        <p v-if="userData" style="line-height: 27px"><img :src="require('../assets/images/leave'+(userData.memberLevel <= 5 ?userData.memberLevel:((Number(userData.memberLevel)/5)-1))+'.png')" alt=""
                                           class="sign"/>{{ userData.memberLevel | leveChange }}</p>
      </div>
    </div>
    <div :style="{zIndex:singOutVisible?'2':'5'}" class="user-btn flex">
      <div>
        <el-popover
            placement="top"
            width="488"
            popper-class="cart-popper">
          <p style="text-align: left;font-size: 20px" v-if="cartList.length === 0">Cart is empty, why not take a look at our menu!</p>
          <div class="goods-detail" v-for="(item,index) in cartList" :key="index">
            <div class="flex">
              <div><img :src="item.picUrl" alt=""></div>
              <div class="detail">
                <p style="overflow: hidden;width: 280px;height: 30px;">{{ item.name }}</p>
                <p v-if="!item.cateName" style="overflow: hidden;width: 280px;height: 28px;"><span
                    v-for="(data,key,i) in item.specifications" :key="i">{{ item.specifications[key] }} </span></p>
                <p>£{{ item.total }}</p>
              </div>
            </div>
            <div class="operate">
              <div class="num">
                <el-input-number v-model="item.num" :min="1" @change="handleAdd(item,index)"></el-input-number>
              </div>
              <div class="del" @click="handleDel(item,index)"><i class="el-icon-delete"></i></div>
            </div>
          </div>
          <div class="payment-btn" v-if="cartList.length > 0">
            <el-button @click="handlePassword">Payment</el-button>
          </div>
          <div class="cart" slot="reference">
            <img width="35px" src="../assets/images/cart.png" alt=""/>
            <div class="cart-num">{{ cartList.length }}</div>
          </div>
        </el-popover>
      </div>
      <div>

        <el-popover
            placement="top"
            width="388"
            popper-class="reward-popper">
          <p style="text-align: left;font-size: 20px" v-if="!clientData.rewardList">No notifications at this time</p>
          <div v-for="(item,index) in clientData.rewardList" :key="index" class="reward">
            <p :style="{cursor: item.reward !== null?'pointer':''}" @click="handleReward(item)">
              <img :src="require('../assets/images/reward'+item.type+'.png')" alt=""/>
              {{ item.msg }}
            </p>
          </div>
          <div class="cart" slot="reference">
            <img width="26px" src="../assets/images/msg.png" alt=""/>
            <div class="reward-num">{{ clientData.rewardList?clientData.rewardList.length:0 }}</div>
          </div>
        </el-popover>
      </div>
      <el-tooltip class="item" effect="dark" content="" placement="bottom">
        <div @click="handleCloseTra('trayon')" style="margin-top: -10px">
          <span id="close"></span>
        </div>
      </el-tooltip>
    </div>
    <div class="index">
      <el-tabs v-model="activeName" v-if="tabData" @tab-click="tabChange">
        <el-tab-pane v-for="(item,index) in tabData" :key="index" :name="item.cateName">
          <span slot="label" v-if="item.cateName !== 'TopUp'">{{ item.cateName }}</span>
          <goods v-if="activeName===item.cateName&&item.templateType !== 1&&userData" :cateName="item.cateName" :userData="userData"
                 :goods="item.goods" :subCategory="item.subCategory"></goods>
          <tab-stroe v-if="activeName===item.cateName&&item.templateType === 1&&!showDetail" :cateName="item.cateName"
                     :goods="item.goods" @handleStoreDetail="handleStoreDetail"></tab-stroe>
          <store-detail v-if="showDetail" :cateName="item.cateName" :storeDetail="storeDetail"></store-detail>
        </el-tab-pane>
      </el-tabs>

      <!--      <div class="footer" v-if="activeName !== 'TopUp'">-->
      <!--        <div class="footer-content">-->
      <!--          <div class="total" style="margin-right: 300px">-->
      <!--            <p>Total</p>-->
      <!--            <p>£ {{ total }}</p>-->
      <!--          </div>-->
      <!--          <div class="pay-btn">-->
      <!--            <img src="../assets/images/cart.png" alt=""-->
      <!--                 @click="typeStatus?paymentAdminVisible=true:paymentVisible=true">-->
      <!--            <el-popover-->
      <!--                placement="top"-->
      <!--                width="489"-->
      <!--                v-model="visible">-->
      <!--              <div class="goods-detail" v-for="(item,index) in cartList" :key="index">-->
      <!--                <div class="flex">-->
      <!--                  <div><img :src="item.picUrl" alt=""></div>-->
      <!--                  <div class="detail">-->
      <!--                    <p style="overflow: hidden;width: 280px;height: 30px;">{{ item.name }}</p>-->
      <!--                    <p style="overflow: hidden;width: 280px;height: 28px;"><span-->
      <!--                        v-for="(data,key,i) in item.specifications" :key="i">{{ item.specifications[key] }} </span></p>-->
      <!--                    <p>£{{ item.total }}</p>-->
      <!--                  </div>-->
      <!--                </div>-->
      <!--                <div class="operate">-->
      <!--                  <div class="num">-->
      <!--                    <el-input-number v-model="item.num" :min="1" @change="handleAdd(item,index)"></el-input-number>-->
      <!--                  </div>-->
      <!--                  <div class="del" @click="handleDel(item,index)"><i class="el-icon-delete"></i></div>-->
      <!--                </div>-->
      <!--              </div>-->
      <!--              <div class="cart" slot="reference">-->
      <!--                <div class="cart-num">{{ cartList.length }}</div>-->
      <!--              </div>-->
      <!--            </el-popover>-->
      <!--          </div>-->
      <!--        </div>-->
      <!--      </div>-->

      <payment v-if="paymentVisible" :paymentData="{goodsList:cartList,total:total}" :paymentVisible="paymentVisible"
               @handlePayClose="handlePayClose"></payment>

      <payment-admin v-if="paymentAdminVisible" :paymentData="{goodsList:cartList,total:total}"
                     :paymentAdminVisible="paymentAdminVisible"
                     @handlePayAdminClose="handlePayAdminClose"></payment-admin>

      <success v-if="successVisible" :successVisible="successVisible"></success>
      <error v-if="errorVisible" :errorVisible="errorVisible"></error>
      <login v-if="loginVisible" :loginVisible="loginVisible" @handleLoginClose="handleClose"
             @handleAdminLogin="handleAdminLogin"></login>
      <lockPc v-if="lockPcVisible" :lockPcVisible="lockPcVisible" @handleClose="handleClose"
              @handleAdminLogin="handleAdminLogin"></lockPc>
      <password v-if="passwordVisible" :passwordVisible="passwordVisible"
                @handleClose="handlePayClose" @handlePayment="handlePayment"></password>
      <qrCode v-if="qrCodeVisible" :qrCodeVisible="qrCodeVisible"
              @handleClose="handleClose" :type="type"></qrCode>
      <signOut v-if="singOutVisible" :singOutVisible="singOutVisible" :userData="userData" :clientData="clientData"
               :signOutData="signOutData"
               @handleClose="handleClose" :type="type" @handleCloseTra="handleCloseTra"></signOut>
    </div>
  </div>
</template>

<script>
import Goods from "../components/goods";
import payment from '../components/payment'
import {getAllGoods, getUserData, logout, rewardSave} from "@/api/shopMall";
import {mapState} from 'vuex'
import calculation from "../utils/calculation";
import Success from "../components/success";
import PaymentAdmin from "../components/payment-admin";
import Error from "../components/error";
import Login from "@/components/login";
import f from "@/utils/communication";
import tabStroe from '../components/store'
import lockPc from '../components/lockPc'
import StoreDetail from "@/components/storeDetail";
import password from '../components/password'
import qrCode from '../components/qrCode'
import signOut from '../components/signOut'
export default {
  name: "index",
  components: {
    StoreDetail,
    Login,
    Error,
    PaymentAdmin,
    Success,
    Goods,
    payment,
    tabStroe,
    lockPc,
    password,
    qrCode,
    signOut
  },
  filters: {
    changeTime(v) {
      let date = Number(new Date().getTime()) / 1000
      let theTime = date - v
      let theTime1 = 0;// 分
      let theTime2 = 0;// 小时
      if (theTime > 60) {
        theTime1 = Number(theTime / 60);
        theTime = Number(theTime % 60);
        if (theTime1 > 60) {
          theTime2 = Number(theTime1 / 60);
          theTime1 = Number(theTime1 % 60);
        }
      }
      let result = "";
      result = "" + Math.round(theTime1) + "m" + result;
      result = "" + Math.round(theTime2) + "h" + result;
      return result;
    },
    leveChange(v) {
      let val = ''
      switch (v) {
        case 0:
          val = 'Normal'
          break;
        case 1:
          val = 'GOLD'
          break;
        case 2:
          val = 'Platinum'
          break;
        case 3:
          val = 'Diamond'
          break;
        case 4:
          val = 'Corporate(Team)'
          break;
      }

      return val
    }
  },
  data() {
    return {
      activeName: '1',
      visible: false,
      paymentVisible: false,
      lockPcVisible: false,
      paymentAdminVisible: false,
      passwordVisible: false,
      qrCodeVisible: false,
      singOutVisible: false,
      balanceCharge: false,
      showDetail: false,
      popover: false,
      tabData: [],
      userData: '',
      signOutData: '',
      num: 1,
      typeStatus: false,
      loginVisible: false,
      isManager: false,
      storeDetail: '',
      type: 0
    }
  },
  computed: {
    ...mapState({
      cartList: state => state.cart.cartList,
      total: state => state.cart.totalMoney,
      successVisible: state => state.success.successVisible,
      errorVisible: state => state.error.errorVisible,
      extraPrice: state => state.comData.extraPrice,
      comData: state => state.comData.comData,
      clientData: state => state.clientMessage.clientData !== null ? state.clientMessage.clientData : ''
    })
  },

  mounted() {
    this.getData()
  },
  methods: {
    /**
     * 获取所有商品数据
     */
    getData() {
      let device = {}
      let data = this.getQueryString('data')
      // let data = JSON.stringify({
      //   "store_id": 10,
      //   "memberCode": "UK20021778",
      //   "deviceIp": "192.0.0.1",
      //   "memberId": "16884",
      //   'authCode': '0',
      //   'appointmentMsg':'The computer was booked from 19:00 to 21:00'
      // })
      if (this.isJSON(data)) {
        data = JSON.parse(data)
        if (data.appointmentMsg) {
          this.$alert(data.appointmentMsg, {
            confirmButtonText: 'OK',
            customClass: 'warn',
            center: true,
            callback: action => {
              console.log(action)
            }
          })
        }
        device.typeStatus = false
        this.typeStatus = false
        device.data = data
        this.creatData(device)
      } else {
        this.loginVisible = true
      }
    },

    handleAdminLogin(v) {
      this.loginVisible = false
      let device = {}
      device.typeStatus = true
      device.data = v
      this.typeStatus = true
      this.isManager = v.isManager
      this.creatData(device)
    },

    creatData(device) {
      this.$store.dispatch('comData/getComData', device)
      getAllGoods(device.data).then(res => {
        this.tabData = res.data.allStoreGoods
        this.$store.dispatch('comData/getExtraPrice', res.data.extraPrice)
        this.activeName = res.data.allStoreGoods[0].cateName
        this.isManager = device.isManager
        console.log(res.data.allStoreGoods)
        let data = res.data.allStoreGoods.filter(item => {
          if(item.cateName == this.activeName) return item
        })
        this.$store.dispatch('comData/getSubCategory',data[0])
      })
      getUserData(device.data).then(res => {
        this.userData = res.data
      })
    },

    // 充值
    handleTopUp() {
      this.type = 0
      this.popover = false
      this.singOutVisible = false
      this.paymentVisible = false
      this.lockPcVisible = false
      this.passwordVisible = false
      this.qrCodeVisible = true
    },

    // 下载app
    handleDownApp() {
      this.type = 1
      this.popover = false
      this.singOutVisible = false
      this.paymentVisible = false
      this.lockPcVisible = false
      this.passwordVisible = false
      this.qrCodeVisible = true
    },

    // 关闭
    handleClose() {
      this.loginVisible = false
      this.lockPcVisible = false
      this.qrCodeVisible = false
      this.singOutVisible = false
    },

    // 判断是否json
    isJSON(str) {
      if (typeof str == 'string') {
        try {
          var obj = JSON.parse(str);
          if (typeof obj == 'object' && obj) {
            return true;
          } else {
            return false;
          }

        } catch (e) {
          console.log('error：' + str + '!!!' + e);
          return false;
        }
      }
      console.log('It is not a string!')
    },

    getQueryString(name) {
      const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
      const r = window.location.search.substr(1).match(reg) || window.location.hash.substring((window.location.hash.search(/\?/)) + 1).match(reg);
      if (r != null) {
        return decodeURIComponent(r[2]);
      }
    },

    handleReward(item){
      if(item.reward !== null){
        let data = this.comData
        data.reward = item.reward
        rewardSave(data).then(res => {
          if(res){
            this.$message.success(res.msg)
          }
        })
      }
    },

    /**
     * 关闭支付弹窗
     */
    handlePayClose() {
      this.paymentVisible = false
      this.passwordVisible = false
    },
    /**
     * 关闭支付弹窗
     */
    handlePayAdminClose() {
      this.paymentAdminVisible = false
    },

    // 购物车删除
    handleDel(item, index) {
      let data = {data: item, index: index}
      this.$store.dispatch('cart/delCart', data)
    },

    // 锁屏
    handleLockPc() {
      this.popover = false
      this.paymentVisible = false
      this.qrCodeVisible = false
      this.passwordVisible = false
      this.singOutVisible = false
      this.lockPcVisible = true
    },

    //验证密码
    handlePassword() {
      this.popover = false
      this.paymentVisible = false
      this.lockPcVisible = false
      this.qrCodeVisible = false
      this.singOutVisible = false
      this.passwordVisible = true
    },
    // 支付
    handlePayment() {
      this.popover = false
      this.passwordVisible = false
      this.lockPcVisible = false
      this.qrCodeVisible = false
      this.singOutVisible = false
      this.paymentVisible = true
    },

    // tab切换
    tabChange() {
      this.showDetail = false
      this.storeDetail = ''
      getAllGoods(this.comData).then(res => {
        this.tabData = res.data.allStoreGoods
        this.$store.dispatch('comData/getExtraPrice', res.data.extraPrice)
        let data = res.data.allStoreGoods.filter(item => {
          return item.cateName == this.activeName
        })
        this.$store.dispatch('comData/getSubCategory',data[0])
      })
    },

    // store详情
    handleStoreDetail(v) {
      this.showDetail = true
      this.storeDetail = v
    },

    // 添加购物车
    handleAdd(data, index) {
      let good = JSON.parse(JSON.stringify(data))
      let unit = 0
      let extraPrice = JSON.parse(this.extraPrice)
      for (const key in good.specifications) {
        if (typeof good.specifications[key] == "string") {
          if (extraPrice[good.specifications[key]] !== undefined) {
            unit = calculation.accAdd(extraPrice[good.specifications[key]], unit)
          }
        } else {
          good.specifications[key].forEach(item => {
            if (extraPrice[item] !== undefined) {
              unit = calculation.accAdd(extraPrice[item], unit)
            }
          })
        }
      }
      unit = calculation.accAdd(good.retailPrice, unit)
      good.total = calculation.accMul(good.num, unit)
      this.$store.dispatch('cart/editCart', {good, index})
    },

    // 推出
    handleSignOut() {
      logout({memberId: this.comData.memberId, storeId: this.comData.store_id, deviceIp: this.comData.deviceIp})
          .then((res) => {
            if (res) {
              this.signOutData = res.data
              this.popover = false
              this.singOutVisible = true
              this.passwordVisible = false
              this.lockPcVisible = false
              this.qrCodeVisible = false
              this.paymentVisible = false
            }
          })
    },
    handleCloseTra(v) {
      f.handleOut(v)
    },
  }
}
</script>

<style scoped lang="scss">
.app-content {
  .user {
    position: fixed;
    left: 26px;
    top: 20px;
    display: flex;
    justify-content: flex-start;
    color: #FFB24F;
    z-index: 5;

    .name {
      font-size: 26px;
      color: #ffffff;
      margin-bottom: 6px;
    }

    img {
      width: 62px;
      height: 70px;
      margin-right: 20px;
      float: left;
    }

    ::v-deep .el-popover__reference {
      width: 74px;
      height: 74px;
      margin-right: 20px;
      position: relative;

      .head-img {
        width: 70px;
        height: 70px;
        position: absolute;
        border-radius: 50%;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        padding-top: 5px;
      }

      .bg {
        width: 74px;
        height: auto;
        position: relative;
        z-index: 3;
      }
    }
  }

  .user-btn {
    position: fixed;
    right: 20px;
    top: 20px;
    z-index: 5;

    img {
      margin-right: 30px;
    }

    ::v-deep .cart {
      position: relative;

      .cart-num {
        width: 18px;
        height: 18px;
        border-radius: 50%;
        background: #FFD40E;
        position: absolute;
        top: 2px;
        right: 20px;
        color: #000000;
        line-height: 18px;
        font-size: 12px;
        text-align: center;
      }

      .reward-num{
        width: 18px;
        height: 18px;
        border-radius: 50%;
        background: #FFD40E;
        position: absolute;
        top: -2px;
        right: 24px;
        color: #000000;
        line-height: 18px;
        font-size: 12px;
        text-align: center;
      }
    }
  }

  .flex {
    display: flex;
    justify-content: flex-start;
    align-items: center;
  }

  .index {
    width: 100%;
    height: 100%;
    position: absolute;
    overflow: hidden;
    z-index: 3;
    top: 0;
    left: 0;

    ::v-deep .el-tabs {
      height: calc(100% - 60px);
      padding-top: 15px;

      .el-tabs__nav-scroll {
        text-align: center;
      }

      .el-tabs__content {
        height: calc(100% - 75px);

        .el-tab-pane {
          height: 100%;
        }
      }
    }

    ::v-deep .el-tabs__nav-wrap::after {
      height: 0;
    }

    ::v-deep .el-tabs__nav-scroll {
      padding-left: 40px;
      height: 60px;

      .el-tabs__nav {
        height: 100%;
        margin: 0 auto;
        float: none;
      }

      .el-tabs__item {
        padding: 0;
        height: 100%;
        font-size: 20px;
        color: #ffffff;

        span {
          margin: 0 20px;
        }
      }

      .el-tabs__item.is-active {
        color: #FFD40E;
      }

      .el-tabs__active-bar {
        display: none;
      }
    }

  }

}


</style>
